package com.wzqj.agent.app.login.controller;

import com.wzqj.agent.app.user.domain.AppToken;
import com.wzqj.agent.common.redis.CacheClient;
import com.wzqj.agent.common.redis.CacheKey;
import com.wzqj.agent.util.TokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;

/**
 * 权限控制
 * Created by wanghao@weipass.cn on 2015/7/30.
 */
@Controller
@RequestMapping("/api/auth")
public abstract class AuthRequiredController {

    public enum RmCode {
        PASS,// 通过
        REQUIRE_LOGIN,// 需要登录
        REQUIRE_AUTH// 需要权限
    }

    @Autowired
    private CacheClient cacheClient;

    // 控制器方法的前置方法
    public RmCode preMethod(HttpServletRequest request, HttpServletResponse response){

        String wid = request.getParameter("wid");
        String mk = request.getParameter("mk");
        String mt = request.getParameter("mt");
        String appToken = request.getParameter("appToken");
        if(StringUtils.isEmpty(appToken) || StringUtils.isEmpty(wid) || StringUtils.isEmpty(mt) || null == mk){//appToken不存在未登录
            return RmCode.REQUIRE_LOGIN;// 需要登录
        } else {
            try {
                AppToken token = TokenUtil.strToToken(appToken);
                String id = token.getWid();
                String mid = token.getMk();
                String mtype = token.getMt();
                if(!id.equals(wid) || !mid.equals(mk) || !mtype.equals(mt)){//手机唯一编号或登录id与token不一致，非app请求
                    return RmCode.REQUIRE_AUTH;// 需要权限
                }else{
                    Object cache = cacheClient.get(CacheKey.用户令牌 + wid);
                    if(null == cache || !appToken.equals(cache.toString())){//token失效
                        return RmCode.REQUIRE_AUTH;// 需要权限
                    }
                }
            } catch (Exception e) {
                return RmCode.REQUIRE_LOGIN;// 需要登录
            }
        }
        return RmCode.PASS;
    }

}

